import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import * as api from '@/api'

export interface AnalysisData {
  total_logs: number
  unique_components: number
  duplicate_ratio: number
  duplicate_count: number
  most_active_components: [string, any][]
  time_patterns: any
  components: any
  duplicates: any
}

export const useAnalysisStore = defineStore('analysis', () => {
  // 状态
  const analysisData = ref<AnalysisData | null>(null)
  const loading = ref(false)
  const uploadProgress = ref(0)

  // 计算属性
  const hasData = computed(() => analysisData.value !== null)
  const totalLogs = computed(() => analysisData.value?.total_logs || 0)
  const uniqueComponents = computed(() => analysisData.value?.unique_components || 0)
  const duplicateRatio = computed(() => analysisData.value?.duplicate_ratio || 0)

  // 上传文件
  const uploadFile = async (file: File) => {
    try {
      loading.value = true
      uploadProgress.value = 0
      
      const response = await api.uploadFile(file)
      
      if ((response as any).error) {
        ElMessage.error((response as any).error)
        return false
      }
      
      ElMessage.success('文件上传成功')
      // 上传成功后，不再自动加载概览分析数据，因为概览页面已删除
      // analysisData.value 会在 HomeView.vue 中的 session 恢复逻辑中设置
      return true
    } catch (error: any) {
      ElMessage.error(`上传失败: ${error.message}`)
      return false
    } finally {
      loading.value = false
      uploadProgress.value = 0
    }
  }

  // 从会话数据加载分析结果 (此函数用于从现有会话ID加载，它会触发后端恢复会话到内存)
  const loadAnalysisFromSession = async (sessionId: string) => {
    try {
      loading.value = true
      
      // 调用后端加载会话到内存，并返回其 analysis_results
      const loadResponse = await api.loadSessionToMemory(sessionId)
      
      if ((loadResponse as any).error) {
        ElMessage.error((loadResponse as any).error)
        return
      }
      
      // 后端加载会话时已将 analysis_results 存储在 log_processor 中
      // 此处不再需要重新从 /analysis API 获取，直接设置 analysisData
      // 但后端 loadSessionToMemory 接口不再返回 analysis_results 字段
      // 而是通过 uploadFile 或 setAnalysisFromSession 来设置
      ElMessage.success('会话已成功加载到内存')
    } catch (error: any) {
      ElMessage.error(`加载会话数据失败: ${error.message}`)
    } finally {
      loading.value = false
    }
  }

  // 从会话对象直接设置分析数据（用于从工作区store获取的数据）
  const setAnalysisFromSession = (sessionData: any) => {
    if (sessionData && sessionData.analysis_results) {
      analysisData.value = sessionData.analysis_results
    }
  }

  // 清空数据
  const clearData = () => {
    analysisData.value = null
  }

  return {
    // 状态
    analysisData,
    loading,
    uploadProgress,
    
    // 计算属性
    hasData,
    totalLogs,
    uniqueComponents,
    duplicateRatio,
    
    // 方法
    uploadFile,
    loadAnalysisFromSession,
    setAnalysisFromSession,
    clearData
  }
}) 